package com.webull.information.center.carwler.common.util.jsoup.prase_cn;

import java.util.Date;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.webull.information.center.carwler.common.model.NewsInformation;
import com.webull.information.center.carwler.common.util.jsoup.HtmlBodyPrase;
import com.webull.information.center.carwler.common.util.jsoup.JsoupPraseUtil;

/**
 * 新浪财经频道网页解析,
 * 
 * @author shimingjun
 * @date 2016年6月28日 下午12:48:17
 * @version 1.0
 * @since JDK 1.8
 */
public class Sina_TWHtmlPrase implements HtmlBodyPrase {
	protected final Logger logger = LogManager.getLogger(getClass());

	@Override
	public void praseNewsInfo(org.jsoup.nodes.Document doc, NewsInformation info) {
		try {
			Element body = doc.getElementById("articles");
			String source_newtime = body.getElementsByTag("cite").first().html();// <cite>北京新浪網
																					// (2016-05-31
																					// 00:53)</cite>
			String source = StringUtils.substringBefore(source_newtime, "(");
			String newtime = StringUtils.substringBetween(source_newtime, "(", ")");
			info.setSourceName(source);

			info.setPushTime(newtime);
			Element article_content = body.getElementById("article_content");
			Element pcont = article_content.getElementsByClass("pcont").first();
			// Element div = pcont.getElementsByTag("div").first();
			Elements pes = pcont.getElementsByTag("P");

			for (int i = pes.size(); pes != null && i > 0; i--) {
				if (!StringUtils.isBlank(pes.get(i - 1).html())) {
					Element p = pes.get(i - 1);
					try {
						p.attr("style", "text-indent:2em;");
						Elements ss = p.select("span[class=kword]");// 替换kword的标签
						for (int j = 0; ss != null && j < ss.size(); j++) {
							// String t =
							// ss.get(j).getElementsByTag("A").html();
							// ss.get(j).replaceWith(new TextNode(t, ""));
							JsoupPraseUtil.replaceWithText(ss.get(j));
						}
					} catch (Exception e) {

					}
				} else {
					pes.remove(i - 1);
				}
			}

			info.setContent(pes.outerHtml());
			if (!StringUtils.isBlank(newtime)) {
				Date d = DateUtils.parseDate(newtime, "yyyy-MM-dd HH:mm");
				info.setNewsTime(d);
			}
			// String main_pic =
			// article_content.select("img").first().attr("src");
			// if (!StringUtils.isEmpty(main_pic)) {
			// main_pic = HtmlPrase.procImgSrc(new URL(info.getUrl()),
			// main_pic);
			// info.setMainPic(main_pic);
			// }

		} catch (Exception e) {
			logger.warn(e);
		}
	}

}
